package com.gzs.learn.payment.algorithm;

import com.gzs.learn.inf.BaseResponseDto;
import com.gzs.learn.payment.clients.ISerialQueryClient;
import com.gzs.learn.payment.inf.exception.PaymentException;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @author zhisong.guan
 */
@Component
@RequiredArgsConstructor
public class SegmentKeyGenerator implements ShardingKeyGenerator {
    private static final String PAYMENT_INCREMENT = "payment_increment";
    private final ISerialQueryClient serialQueryClient;

    @Override
    public String getType() {
        return "segment";
    }

    @Override
    public Properties getProperties() {
        return null;
    }

    @Override
    public void setProperties(Properties properties) {
    }

    @Override
    public Comparable<?> generateKey() {
        BaseResponseDto<Long> segmentResp = serialQueryClient.getSegmentId(PAYMENT_INCREMENT);
        if (BaseResponseDto.isSuccess(segmentResp)) {
            return segmentResp.getData();
        }
        throw new PaymentException(segmentResp.getMsg());
    }

}
